﻿<#
    本脚本用于验证一些操作
#>

# 视频录制的实时存储路径
$video_file_path = "/sdcard/test_video1019.mp4"
# 本地存储绝对路径
$local_video_path = "E:\工作项目\高精地图_车机性能测试\视频文件"

$device_sn = "1B0D323534574601"

#$script = "E:\工作项目\高精地图_车机性能测试\record.ps1  -device_sn '{0}' -video_file_path '{1}'" -f $device_sn, $video_file_path
$script = "E:\工作项目\高精地图_车机性能测试\record.ps1"

function video_record_start($video_name_path)
{
   $job = Start-Job -ScriptBlock {adb -s $device_sn shell screenrecord --bugreport --time-limit 120 $video_name_path}
   Write-Output $job 
   # 确认任务已启动
   $job_info = Get-Job -Name $job.Name
   if ($job_info.count > 0) {
        if($job_info.State -icontains "running"){
            Write-Host "已启动录制视频，视频位置在 $video_name_path"
        }
   }
   else{
        Write-Host "没有找到视频录制的后台任务"
   }
    return $job.Name
}

function cDir($path)
<#
    替代cd 命令与set-location命令
    解决window本地的盘符跨越问题
#>
{
    # 先判断本地路径是否存在
    if (Test-Path $path){
        Set-Location $path
        if ($(Get-Location).Path.CompareTo($path)){
            Write-Host "已进入指定的路径 $path"
        }
        return 1
    }
    else {
        Write-Host "本地不存在此路径，创建并进入此路径"
        mkdir $path -Force
        if (Test-Path $path)
        {
            Write-Host "本地创建成功"
            cDir $path
        }
    }
}

function stop_video_record($params)
<#
    本函数停止录制并删除已录制的原始文件
        params:: job_name : 后台录制线程任务
        params:: local_save_path : 拷贝到本地目录
        params:: video_name : andriod中的视频文件所在路径
#>
{
    $job_name = $params[0]
    $local_save_path = $params[1]
    $video_name = $params[2]
    # 判断是否还在继续
    $job_exist = Get-Job -Name $job_name
    if ($job_exist)
    {
        # 判断状态给出提示
        if (-not $job_exist.State -icontains "running"){
            Write-Host "视频录制因外部原因已被中断，当前没有再录制视频"
        }
        else
        {
            $all_ps = Get-Process | where {$_.Name -like "powershell"}
            Write-Host $all_ps
            $process_id = $(Get-Process | where {$_.Name -like "powershell"} | select id -Last 1).id

            #Stop-Process -Id $process_id
            Stop-Job -Name $job_name
        }
        # 删除任务名称
        Remove-Job -Name $job_name
        # 拷贝出来
        cDir $local_video_path
        adb pull $video_name $local_save_path
        # 确保已正确的导出到本地
        if (Test-Path $local_save_path){
            Write-Host "已导出到本地文件夹: $local_save_path"
        }
        # 执行删除
        Write-Host "正在执行删除android文件操作"
        adb shell rm -f $video_name
        return 1
    }
    else
    {
        Write-Host "无可执行的停止的任务"
        return 0
    }
}


adb root

#$job_id = video_record_start $video_file_path

$job = Start-Job -FilePath $script -ArgumentList $device_sn, $video_file_path

$job_id = $job.Name
$job_stat = $job.State
Write-Output $job_id $job_stat

Start-Sleep 10
$job_stat = $job.State
Write-Output $job_stat
stop_video_record($job_id, $local_video_path, $video_file_path)


